<template>
  <div class="add">
    <!-- header -->
    <el-card class="box-card">
      <div class="header">
        <div class="item-tl">
          <span class="n"> 主题</span>
          <el-input
            placeholder="请输入内容"
            prefix-icon="el-icon-tickets"
            v-model="atricle.title"
            size="small"
          >
          </el-input>
        </div>
        <div class="item-lm">
          <span class="n">栏目</span>
          <el-select
            class="select"
            v-model="atricle.classify"
            size="small"
            placeholder="请选择"
          >
            <el-option
              v-for="item in articleClassify"
              :key="item.id"
              :label="item.value"
              :value="item.value"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="u-sv">
        <div class="tp-upload">
          <div class="up-msg"><span>封面图片上传</span></div>
          <UploadPicture @fileNameEvn="getFileName" @removeFileEvn='removeFile' :files='atricle.fileName' :limit="1" />
        </div>
        <div>
          <el-tooltip
            :content="isEdit ? '保存' : '创建'"
            placement="top"
            effect="light"
          >
            <el-button
              type="primary"
              @click="handelSumbit"
              icon="el-icon-check"
              circle
            ></el-button>
          </el-tooltip>
        </div>
      </div>
    </el-card>

    <!-- 文章编辑器 -->
    <div id="editor">
      <mavon-editor
        style="height: 100%; width: 100%"
        v-model="atricle.content"
        ref="md"
        @imgAdd="handleEditorImgAdd"
        @imgDel="handleEditorImgDel"
      ></mavon-editor>
    </div>
  </div>
</template>

<style lang="scss" scope>
.add {
  min-height: 800px;
}
.u-sv {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}
.tp-upload {
  display: flex;
  margin-top: 20px;
  .up-msg {
    // background-color: rgb(250, 236, 211);
    margin-right: 18px;
    display: flex;
    align-items: center;
    font-size: 14px;
  }
}
.header {
  display: flex;

  .item-tl {
    display: flex;
    font-size: 14px;
    align-items: center;
    .n {
      width: 50px;
    }
  }
  .item-lm {
    display: flex;
    font-size: 14px;
    align-items: center;
    margin-left: 50px;
    .n {
      width: 38px;
    }
  }
  .select {
    width: 120px;
  }
}
</style>

<script>
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import { uploadFiles } from '../../api/upload'
import UploadPicture from '../../components/UploadPicture'
import { addArticle, getArticleById, editArticle } from '../../api/article'
import { getArticleClassifyList } from '../../api/classify'

export default {
  data () {
    return {
      articleClassify: [],
      isEdit: false, // false添加文章 true编辑文章
      atricle: {
        title: '',
        content: '',
        fileName: '',
        classify: ''
      },
      imgFile: []

    }
  },
  components: {
    mavonEditor,
    UploadPicture
  },
  mounted () {
    getArticleClassifyList({
      pageIndex: 1,
      pageSize: 50
    })
      .then((data) => {
        // console.log(data)

        data.data.data.forEach((item) => {
          this.articleClassify.push({
            id: item.id,
            value: item.articleClassName,
            disabled: !item.isActived
          })
        })
      })
      .catch((err) => {
        console.log(err)
      })

    if (this.$route.name === 'editArticle') {
      this.isEdit = true
      getArticleById(this.$route.params.id)
        .then((res) => {
          this.atricle.title = res.data.data.articleTitle
          this.atricle.content = res.data.data.content
          this.atricle.fileName = res.data.data.resource.resoutceName
          this.atricle.classify = res.data.data.articleClass.articleClassName
          console.log(res)
        })
        .catch((err) => {
          console.log(err)
        })
    }
  },
  watch: {
    $route () {
      this.atricle.title = ''
      this.atricle.content = ''
      this.atricle.fileName = ''
      this.atricle.classify = ''
    }
  },
  methods: {
    async handelSumbit () {
      if (this.atricle.title.trim() <= 0) {
        return this.$message.warning('标题不能为空')
      }
      if (this.atricle.classify.trim() <= 0) {
        return this.$message.warning('栏目不能为空')
      }

      if (this.atricle.content.trim() <= 0) {
        return this.$message.warning('文章内容不能为空')
      }
      const data = {
        articleTitle: this.atricle.title,
        content: this.atricle.content,
        articleClassName: this.atricle.classify,
        resoutceName: this.atricle.fileName
      }
      let res
      if (!this.isEdit) {
        res = await addArticle(data)
      } else {
        res = await editArticle(this.$route.params.id, data)
      }

      if (res.data.code === 200) {
        this.$message.success(res.data.msg)
      } else {
        this.$message.error('添加失败')
      }
      // console.log(res)
    },
    handleEditorImgAdd (pos, $file) {
      const formdata = new FormData()
      formdata.append('file', $file)

      this.imgFile[pos] = $file

      // console.log(this.imgFile)

      uploadFiles(formdata).then((res) => {
        // console.log(res)
        if (res.data.code === 200) {
          console.log('上传成功')

          const url = res.data.data.url
          let name = $file.name
          if (name.includes('-')) {
            name = name.replace(/-/g, '')
          }
          const content = this.atricle.content
          // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)  这里是必须要有的
          if (content.includes(name)) {
            const oStr = `(${pos})`
            const nStr = `(${url})`
            const index = content.indexOf(oStr)
            const str = content.replace(oStr, '')
            const insertStr = (soure, start, newStr) => {
              return soure.slice(0, start) + newStr + soure.slice(start)
            }
            this.atricle.content = insertStr(str, index, nStr)
          }
        } else {
          // this.$Message.error(res.data.msg)
          console.log('上传失败')
        }
      })
    },
    handleEditorImgDel (pos) {
      console.log('删除')
      delete this.imgFile[pos]
    },
    getFileName (data) {
      this.atricle.fileName = data
    },
    removeFile () {
      this.atricle.fileName = ''
    }
  }
}
</script>

<style>
</style>
